<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 商品评价系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            border-radius: 10px;
            margin: 5px 0;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            color: white;
            background: rgba(255,255,255,0.2);
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .content-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }
        .status-badge {
            font-size: 0.8rem;
        }
        .action-buttons .btn {
            margin: 0 2px;
            padding: 5px 10px;
        }
        .search-box {
            background: white;
            border-radius: 25px;
            border: 1px solid #ddd;
            padding: 10px 20px;
        }
        .filter-section {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .table-responsive {
            border-radius: 15px;
            overflow: hidden;
        }
        .table th {
            background: #f8f9fa;
            border: none;
            font-weight: 600;
        }
        .table td {
            border: none;
            vertical-align: middle;
        }
        .pagination {
            justify-content: center;
        }
        .pagination .page-link {
            border-radius: 50%;
            margin: 0 2px;
            border: none;
            color: #667eea;
        }
        .pagination .page-item.active .page-link {
            background: #667eea;
            border-color: #667eea;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-3 col-lg-2 d-md-block sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <h4><i class="fas fa-tachometer-alt me-2"></i>管理后台</h4>
                        <small class="text-muted">欢迎，<span id="adminName">管理员</span></small>
                    </div>
                    
                    <ul class="nav flex-column">
<%--                        <li class="nav-item">--%>
<%--                            <a class="nav-link" href="/product-review/page/admin/dashboard">--%>
<%--                                <i class="fas fa-home me-2"></i>仪表板--%>
<%--                            </a>--%>
<%--                        </li>--%>
                        <li class="nav-item">
                            <a class="nav-link active" href="/product-review/page/admin/users">
                                <i class="fas fa-users me-2"></i>用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/product-review/page/admin/products">
                                <i class="fas fa-box me-2"></i>商品管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/product-review/page/admin/reviews">
                                <i class="fas fa-comments me-2"></i>评价管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/product-review/page/index">
                                <i class="fas fa-arrow-left me-2"></i>返回前台
                            </a>
                        </li>
                        <li class="nav-item mt-3">
                            <a class="nav-link" href="#" onclick="logout()">
                                <i class="fas fa-sign-out-alt me-2"></i>退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content">
                <!-- 顶部导航 -->
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">用户管理</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="refreshUsers()">
                                <i class="fas fa-sync-alt me-1"></i>刷新
                            </button>
                        </div>
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-primary" onclick="showAddUserModal()">
                                <i class="fas fa-plus me-1"></i>添加用户
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 筛选和搜索 -->
                <div class="filter-section">
                    <div class="row align-items-center">
                        <div class="col-md-4">
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-search"></i></span>
                                <input type="text" class="form-control" id="searchInput" placeholder="搜索用户名、邮箱..." onkeyup="searchUsers()">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" id="statusFilter" onchange="filterUsers()">
                                <option value="">全部状态</option>
                                <option value="1">正常</option>
                                <option value="0">禁用</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" id="roleFilter" onchange="filterUsers()">
                                <option value="">全部角色</option>
                                <option value="USER">普通用户</option>
                                <option value="ADMIN">管理员</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-outline-secondary w-100" onclick="resetFilters()">
                                <i class="fas fa-undo me-1"></i>重置
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 用户列表 -->
                <div class="content-card">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">用户列表</h5>
                        <div class="d-flex align-items-center">
                            <span class="text-muted me-3">共 <span id="totalUsers">0</span> 个用户</span>
                            <div class="btn-group btn-group-sm" role="group">
                                <button type="button" class="btn btn-outline-primary" onclick="selectAllUsers()">
                                    全选
                                </button>
                                <button type="button" class="btn btn-outline-danger" onclick="batchDeleteUsers()">
                                    批量删除
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th width="50">
                                        <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                                    </th>
<%--                                    <th width="80">头像</th>--%>
                                    <th>用户名</th>
                                    <th>真实姓名</th>
                                    <th>邮箱</th>
                                    <th>手机</th>
                                    <th>角色</th>
                                    <th>状态</th>
                                    <th>注册时间</th>
                                    <th width="200">操作</th>
                                </tr>
                            </thead>
                            <tbody id="usersTableBody">
                                <!-- 用户列表将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 分页 -->
                    <nav aria-label="用户分页">
                        <ul class="pagination" id="usersPagination">
                            <!-- 分页将通过JavaScript动态生成 -->
                        </ul>
                    </nav>
                </div>
            </main>
        </div>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <div class="modal fade" id="userModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userModalTitle">添加用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="userForm">
                        <input type="hidden" id="userId">
                        <div class="mb-3">
                            <label for="username" class="form-label">用户名 *</label>
                            <input type="text" class="form-control" id="username" required>
                        </div>
                        <div class="mb-3">
                            <label for="realName" class="form-label">真实姓名</label>
                            <input type="text" class="form-control" id="realName">
                        </div>
                        <div class="mb-3">
                            <label for="email" class="form-label">邮箱 *</label>
                            <input type="email" class="form-control" id="email" required>
                        </div>
                        <div class="mb-3">
                            <label for="phone" class="form-label">手机号码</label>
                            <input type="tel" class="form-control" id="phone">
                        </div>
                        <div class="mb-3" id="passwordField">
                            <label for="password" class="form-label">密码 *</label>
                            <input type="password" class="form-control" id="password" required>
                        </div>
                        <div class="mb-3">
                            <label for="role" class="form-label">角色</label>
                            <select class="form-select" id="role">
                                <option value="USER">普通用户</option>
                                <option value="ADMIN">管理员</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="status" class="form-label">状态</label>
                            <select class="form-select" id="status">
                                <option value="1">正常</option>
                                <option value="0">禁用</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveUser()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // 全局变量
        let currentUser = null;
        let userModal = null;
        let allUsers = [];
        let filteredUsers = [];
        let currentPage = 1;
        let pageSize = 10;
        let isEditing = false;
        
        $(document).ready(function() {
            // 初始化模态框
            userModal = new bootstrap.Modal(document.getElementById('userModal'));
            
            // 检查管理员权限
            checkAdminPermission();
            
            // 加载用户列表
            loadUsers();
        });
        
        // 检查管理员权限
        function checkAdminPermission() {
            $.ajax({
                url: '/product-review/user/current',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        currentUser = result.data;
                        if (result.data.role !== 'ADMIN') {
                            alert('您没有管理员权限');
                            window.location.href = '/product-review/page/index';
                            return;
                        }
                        $('#adminName').text(result.data.username);
                    } else {
                        alert('请先登录');
                        window.location.href = '/product-review/page/login';
                    }
                },
                error: function() {
                    alert('请先登录');
                    window.location.href = '/product-review/page/login';
                }
            });
        }
        
        // 加载用户列表
        function loadUsers() {
            $.ajax({
                url: '/product-review/user/list',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200) {
                        allUsers = result.data || [];
                        filteredUsers = [...allUsers];
                        updateUserDisplay();
                    } else {
                        alert('加载用户列表失败：' + result.message);
                    }
                },
                error: function() {
                    alert('加载用户列表失败');
                }
            });
        }
        
        // 更新用户显示
        function updateUserDisplay() {
            $('#totalUsers').text(filteredUsers.length);
            
            // 分页
            const totalPages = Math.ceil(filteredUsers.length / pageSize);
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const pageUsers = filteredUsers.slice(startIndex, endIndex);
            
            // 显示用户列表
            displayUsers(pageUsers);
            
            // 显示分页
            displayPagination(totalPages);
        }
        
        // 显示用户列表
        function displayUsers(users) {
            let html = '';
            
            if (users.length === 0) {
                html = '<tr><td colspan="10" class="text-center text-muted py-4">暂无用户数据</td></tr>';
            } else {
                users.forEach(function(user) {
                    const createTime = new Date(user.createTime).toLocaleDateString();
                    const statusBadge = getStatusBadge(user.status);
                    const roleBadge = getRoleBadge(user.role);
                    console.log("11"+roleBadge)
                    console.log("22"+statusBadge)
                    html += `
                        <tr>
                            <td>
                                <input type="checkbox" class="user-checkbox" value="\${user.id}">
                            </td>
<!--                            <td>-->
<!--                                <img src="/product-review/static/img/default-avatar.jpg" class="user-avatar" alt="头像">-->
<!--                            </td>-->
                            <td>
                                <div class="fw-bold">\${user.username}</div>
                                <small class="text-muted">ID: \${user.id}</small>
                            </td>
                            <td>\${user.realName || '-'}</td>
                            <td>\${user.email || '-'}</td>
                            <td>\${user.phone || '-'}</td>
                            <td>\${roleBadge}</td>
                            <td>\${statusBadge}</td>$
                            <td>\${createTime}</td>
                            <td>
                                <div class="action-buttons">
                                    <button class="btn btn-sm btn-outline-primary" onclick="editUser(\${user.id})" title="编辑">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-warning" onclick="toggleUserStatus(\${user.id})" title="切换状态">
                                        <i class="fas fa-toggle-on"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-info" onclick="resetPassword(\${user.id})" title="重置密码">
                                        <i class="fas fa-key"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteUser(\${user.id})" title="删除">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
                });
            }
            
            $('#usersTableBody').html(html);
        }
        
        // 获取状态徽章
        function getStatusBadge(status) {
            const statusMap = {
                1: { text: '正常', className: 'bg-success' },
                0: { text: '禁用', className: 'bg-danger' }
            };

            const statusInfo = statusMap[status] || { text: '未知', className: 'bg-secondary' };
            return `<span class="badge \${statusInfo.className} status-badge">\${statusInfo.text}</span>`;
        }
        // 获取角色徽章
        function getRoleBadge(role) {
            const roleMap = {
                'USER': { text: '普通用户', className: 'bg-primary' },
                'ADMIN': { text: '管理员', className: 'bg-danger' }
            };
            
            const roleInfo = roleMap[role] || { text: '未知', className: 'bg-secondary' };
            return `<span class="badge \${roleInfo.className} status-badge">\${roleInfo.text}</span>`;
        }
        
        // 显示分页
        function displayPagination(totalPages) {
            let html = '';
            
            if (totalPages <= 1) {
                $('#usersPagination').html('');
                return;
            }
            
            // 上一页
            html += `
                <li class="page-item ${currentPage == 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">
                        <i class="fas fa-chevron-left"></i>
                    </a>
                </li>
            `;
            
            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage || i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
                    html += `
                        <li class="page-item ${i == currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                        </li>
                    `;
                } else if (i === currentPage - 2 || i === currentPage + 2) {
                    html += '<li class="page-item disabled"><span class="page-link">...</span></li>';
                }
            }
            
            // 下一页
            html += `
                <li class="page-item ${currentPage == totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">
                        <i class="fas fa-chevron-right"></i>
                    </a>
                </li>
            `;
            
            $('#usersPagination').html(html);
        }
        
        // 切换页面
        function changePage(page) {
            const totalPages = Math.ceil(filteredUsers.length / pageSize);
            if (page >= 1 && page <= totalPages) {
                currentPage = page;
                updateUserDisplay();
            }
        }
        
        // 搜索用户
        function searchUsers() {
            const keyword = $('#searchInput').val().toLowerCase();
            const statusFilter = $('#statusFilter').val();
            const roleFilter = $('#roleFilter').val();
            
            filteredUsers = allUsers.filter(user => {
                const matchKeyword = !keyword || 
                    user.username.toLowerCase().includes(keyword) ||
                    (user.email && user.email.toLowerCase().includes(keyword)) ||
                    (user.realName && user.realName.toLowerCase().includes(keyword));
                
                const matchStatus = !statusFilter || user.status === statusFilter;
                const matchRole = !roleFilter || user.role === roleFilter;
                
                return matchKeyword && matchStatus && matchRole;
            });
            
            currentPage = 1;
            updateUserDisplay();
        }
        
        // 筛选用户
        function filterUsers() {
            searchUsers();
        }
        
        // 重置筛选
        function resetFilters() {
            $('#searchInput').val('');
            $('#statusFilter').val('');
            $('#roleFilter').val('');
            filteredUsers = [...allUsers];
            currentPage = 1;
            updateUserDisplay();
        }
        
        // 显示添加用户模态框
        function showAddUserModal() {
            isEditing = false;
            $('#userModalTitle').text('添加用户');
            $('#userForm')[0].reset();
            $('#userId').val('');
            $('#passwordField').show();
            $('#password').prop('required', true);
            userModal.show();
        }
        
        // 编辑用户
        function editUser(userId) {
            const user = allUsers.find(u => u.id === userId);
            if (!user) return;
            
            isEditing = true;
            $('#userModalTitle').text('编辑用户');
            $('#userId').val(user.id);
            $('#username').val(user.username);
            $('#realName').val(user.realName || '');
            $('#email').val(user.email || '');
            $('#phone').val(user.phone || '');
            $('#role').val(user.role);
            $('#status').val(user.status);
            $('#passwordField').hide();
            $('#password').prop('required', false);
            
            userModal.show();
        }
        
        // 保存用户
        function saveUser() {
            const userId = $('#userId').val();
            const username = $('#username').val().trim();
            const realName = $('#realName').val().trim();
            const email = $('#email').val().trim();
            const phone = $('#phone').val().trim();
            const password = $('#password').val();
            const role = $('#role').val();
            const status = $('#status').val();
            
            if (!username || !email) {
                alert('请填写必填字段');
                return;
            }
            
            if (!isEditing && !password) {
                alert('请输入密码');
                return;
            }
            
            const userData = {
                username: username,
                realName: realName,
                email: email,
                phone: phone,
                role: role,
                status: status
            };
            
            if (isEditing) {
                userData.id = userId; // 添加用户ID到请求体中
            } else {
                userData.password = password;
            }
            
            const url = isEditing ? '/product-review/user/update' : '/product-review/user/register';
            const method = isEditing ? 'PUT' : 'POST';
            
            $.ajax({
                url: url,
                type: method,
                contentType: 'application/json',
                data: JSON.stringify(userData),
                success: function(result) {
                    if (result.code === 200) {
                        alert(isEditing ? '用户更新成功' : '用户添加成功');
                        userModal.hide();
                        loadUsers();
                    } else {
                        alert('操作失败：' + result.message);
                    }
                },
                error: function() {
                    alert('操作失败');
                }
            });
        }
        
        // 切换用户状态
        function toggleUserStatus(userId) {
            const user = allUsers.find(u => u.id === userId);
            if (!user) return;
            
            const newStatus = user.status === 1 ? 0 : 1;
            
            $.ajax({
                url: `/product-review/user/status`,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify({ userId: userId, status: newStatus }),
                success: function(result) {
                    if (result.code === 200) {
                        alert('用户状态更新成功');
                        loadUsers();
                    } else {
                        alert('状态更新失败：' + result.message);
                    }
                },
                error: function() {
                    alert('状态更新失败');
                }
            });
        }
        
        // 重置密码
        function resetPassword(userId) {
            if (confirm('确定要重置该用户的密码吗？新密码将设置为：123456')) {
                $.ajax({
                    url: `/product-review/user/resetPassword`,
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify({ userId: userId, newPassword: '123456' }),
                    success: function(result) {
                        if (result.code === 200) {
                            alert('密码重置成功，新密码为：123456');
                        } else {
                            alert('密码重置失败：' + result.message);
                        }
                    },
                    error: function() {
                        alert('密码重置失败');
                    }
                });
            }
        }

        function deleteUser(userId) {
            console.log('要删除的用户ID:', userId, '类型:', typeof userId);

            if (typeof userId !== 'number' && !Number.isInteger(userId)) {
                alert('无效的用户ID');
                return;
            }

            if (confirm('确定要删除该用户吗？此操作不可恢复！')) {
                $.ajax({
                    url: `/product-review/user/\${userId}`,
                    type: 'DELETE',
                    success: function(result) {
                        if (result.code === 200) {
                            alert('用户删除成功');
                            loadUsers();
                        } else {
                            alert('删除失败：' + result.message);
                        }
                    },
                    error: function() {
                        alert('删除失败');
                    }
                });
            }
        }
        // 全选/取消全选
        function toggleSelectAll() {
            const selectAll = $('#selectAll').prop('checked');
            $('.user-checkbox').prop('checked', selectAll);
        }
        
        // 选择所有用户
        function selectAllUsers() {
            $('.user-checkbox').prop('checked', true);
            $('#selectAll').prop('checked', true);
        }
        
        // 批量删除用户
        function batchDeleteUsers() {
            const selectedIds = [];
            $('.user-checkbox:checked').each(function() {
                selectedIds.push(parseInt($(this).val()));
            });
            
            if (selectedIds.length === 0) {
                alert('请选择要删除的用户');
                return;
            }
            
            if (confirm(`确定要删除选中的 ${selectedIds.length} 个用户吗？此操作不可恢复！`)) {
                $.ajax({
                    url: '/product-review/user/batch-delete',
                    type: 'DELETE',
                    contentType: 'application/json',
                    data: JSON.stringify(selectedIds),
                    success: function(result) {
                        if (result.code === 200) {
                            alert('批量删除成功');
                            loadUsers();
                            $('#selectAll').prop('checked', false);
                        } else {
                            alert('批量删除失败：' + result.message);
                        }
                    },
                    error: function() {
                        alert('批量删除失败');
                    }
                });
            }
        }
        
        // 刷新用户列表
        function refreshUsers() {
            loadUsers();
        }
        
        // 退出登录
        function logout() {
            $.ajax({
                url: '/product-review/user/logout',
                type: 'POST',
                success: function(result) {
                    if (result.code === 200) {
                        window.location.href = '/product-review/page/index';
                    } else {
                        alert('退出登录失败：' + result.message);
                    }
                },
                error: function() {
                    alert('退出登录失败');
                }
            });
        }
    </script>
</body>
</html>